package com.woniu.adapter;

import com.woniu.exception.UserException;
import com.woniu.outlet.mysql.dao.UserDao;
import com.woniu.outlet.mysql.po.User;
import com.woniu.outlet.mysql.po.UserExample;
import com.woniu.service.domain.UserDo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class UserRepositoryApater {
    @Autowired
    private UserDao userDao;

    /**
     * 注册
     *
     * @param userDo
     */
    public Integer register(UserDo userDo) {
        User user = new User();
        BeanUtils.copyProperties(userDo, user);
        userDao.insert(user);
        return user.getId();
    }

    /**
     * 根据电话号码查询
     *
     * @param phonenumber
     * @return
     */
    public List<User> findByPhoneNum(String phonenumber) {
        UserExample example = new UserExample();
        example.or().andPhonenumberEqualTo(phonenumber);
        List<User> users = userDao.selectByExample(example);
        return users;
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    public UserDo getById(Integer id) {
        User user = userDao.selectByPrimaryKey(id);
        if (user == null) {
            throw new UserException("未查询到该用户");
        }
        UserDo userDo = new UserDo();
        BeanUtils.copyProperties(user, userDo);
        return userDo;
    }

    /**
     * 修改用户信息
     *
     * @param userDo
     */
    public void updateInfo(UserDo userDo) {
        User user = new User();
        BeanUtils.copyProperties(userDo, user);
        log.debug("适配层即将修改的PO对象[{}]", user);
        userDao.updateByPrimaryKey(user);
    }

    /**
     * 条件查询
     *
     * @param example
     * @return
     */
    public List<User> getByExample(UserExample example) {
        List<User> users = userDao.selectByExample(example);
        return users;
    }

}
